package com.icloud.cer.rest.msg.filter;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icloud.cer.rest.msg.MessageHolder;
import com.icloud.cer.rest.msg.MsgConstants;
import com.icloud.cer.rest.util.LogUtils;
import com.icloud.cer.rest.util.MessageUtils;

public class KeepAliveMessageFactoryImpl implements KeepAliveMessageFactory{
	private static final Logger log = LoggerFactory.getLogger(KeepAliveMessageFactoryImpl.class);
	
	@Override
	public boolean isRequest(IoSession session, Object message) {
		if (!(message instanceof MessageHolder)) {
			throw new RuntimeException("Error mina message, or mina handler config error.");
		}
		MessageHolder holder = (MessageHolder)message;
		short command = holder.getCommand();
		if(command == MsgConstants.SERVER_REQ_HEARTBEAT && holder.getSequence() == 0) {
			log.debug("receive client heartbeat response." + command);
			return true;
		}
		return false;
	}

	@Override
	public boolean isResponse(IoSession session, Object message) {
		if (!(message instanceof MessageHolder)) {
			throw new RuntimeException("Error mina message, or mina handler config error.");
		}
		MessageHolder holder = (MessageHolder)message;
		short command = holder.getCommand();
		if(command == MsgConstants.CLIENT_RES_HEARTBEAT && holder.getSequence() == 0) {
			log.debug("server request heartbeat. " + command);
			return true;
		}
		return false;
	}

	@Override
	public Object getRequest(IoSession session) {
		log.debug("get heartbeat message.");
		return MessageUtils.getHeartbeatRequest();
	}

	@Override
	public Object getResponse(IoSession session, Object request) {
		log.info("get heartbeat response.");
		LogUtils.printMessage(log, MsgConstants.CLIENT_RES_HEARTBEAT,session);
		return MessageUtils.getHeartbeatResponse();
	}

}
